/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.cert.CRLException;
import java.security.cert.CertificateException;
import java.security.cert.X509CRL;
import java.security.spec.InvalidKeySpecException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.CA_Service;
import model.CertificateDAO;
import model.FilePathDAO;
import model.KeyIO;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;

/**
 *
 * @author XuanTuan
 */
public class UpdateCertControl extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, CRLException, NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrivateKey privateKey = KeyIO.getPrivateKey(new FileInputStream(getServletContext().getRealPath("\\CAKeys") + "\\pri"));

        String CN = request.getParameter("CN");
        String OU = request.getParameter("OU");
        String O = request.getParameter("O");
        String L = request.getParameter("L");
        String C = request.getParameter("C");
        String certPath = request.getParameter("certPath");

        boolean check = true;
        if (CN.equals("")) {
            request.setAttribute("errorUpdate", "Please input your Common Name!");
            check = false;
        } else if (OU.equals("")) {
            request.setAttribute("errorUpdate", "Please input your Oganazational Unit!");
            check = false;
        } else if (O.equals("")) {
            request.setAttribute("errorUpdate", "Please input your Oganazation!");
            check = false;
        } else if (L.equals("")) {
            request.setAttribute("errorUpdate", "Please input your Locality");
            check = false;
        } else if (C.equals("")) {
            request.setAttribute("errorUpdate", "Please input your Country!");
            check = false;
        }

        if (check == false) {
            RequestDispatcher dispatcherObject = getServletContext().getRequestDispatcher("/UpdateCert.jsp");
            dispatcherObject.forward(request, response);
            return;
        }


        X509CertImpl certImpl = new X509CertImpl(CA_Service.getCert(new FileInputStream(certPath)));
        String serialCertImpl = certImpl.getSerialNumber() + "";
        X509CertImpl certUpdate = null;
        String certPathUpdate = "";
        try {
            //update cert
            certUpdate = CA_Service.updateCert(new FileInputStream(certPath), new X500Name("CN=" + CN + ", OU=" + OU + ", O=" + O + ", L=" + L + ", C=" + C), privateKey);

            //write cert update to file
            certPathUpdate = getServletContext().getRealPath("\\Certificates") + "\\" + certUpdate.getSerialNumber() + "_" + CN + ".cer";
            FileOutputStream fileOutputStream = new FileOutputStream(certPathUpdate);
            fileOutputStream.write(certUpdate.getEncoded());
            fileOutputStream.close();



        } catch (Exception ex) {
            ex.printStackTrace();
        }

        //revoke old cert
        FileInputStream certin = null;
        X509CRL x509crl = null;
        X509CRL x509crlUpdate = null;
        try {
            certin = new FileInputStream(getServletContext().getRealPath("\\CRL") + "\\crl.crl");
            x509crl = CA_Service.getCRL(certin, privateKey);
            x509crlUpdate = CA_Service.revokeCert(x509crl, certImpl, privateKey);
            certin.close();
        } catch (Exception e) {
            x509crlUpdate = CA_Service.revokeCert(null, certImpl, privateKey);
        }

        //write new crl to file
        FileOutputStream fileOutputStream = new FileOutputStream(getServletContext().getRealPath("\\CRL") + "\\crl.crl");
        fileOutputStream.write(x509crlUpdate.getEncoded());
        fileOutputStream.close();

        //update database
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("user");
        CertificateDAO.deleteCert(serialCertImpl);
        CertificateDAO.addCert(certUpdate.getSerialNumber() + "", username, certUpdate.getNotAfter(), certUpdate.getNotBefore(), certPathUpdate,"Certificates/" + certUpdate.getSerialNumber() + "_" + CN + ".cer");
        FilePathDAO.saveFilePath("crl", getServletContext().getRealPath("\\CRL\\crl.crl"));

        response.sendRedirect("./ManagerCert.jsp");
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (CertificateException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CRLException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SignatureException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (CertificateException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CRLException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SignatureException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(UpdateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
